import axios from 'axios'
import {BASE_URL} from '@/config/api'
import router from '@/routes/index'
import {message} from 'element-ui'
import * as tokenTools from '@/utils/tokenTools.js'
import {getToken} from '@/utils/tokenTools.js'
import qs from 'qs'

const service = axios.create({
    baseURL: process.env.NODE_ENV === 'production' ? BASE_URL : '/api/',
    timeout: 50000, // 请求超时uploadBuildExcel
    responseType: 'json',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'token': getToken()
    },
})

service.interceptors.request.use(config => {
    console.log(tokenTools.getExpiration())
    if (!config.headers.token && tokenTools.getToken()) {
        config.headers.token = tokenTools.getToken()
    }
    return config
})

let lastCode = ''
service.interceptors.response.use(res => res, error => {
    const code = error.toString().match(/\s\d{3}(\s|$)/)?.[0]?.trim()
    if ([401, 402, 403].includes(Number(code))) {
        service({
            url: 'login/referToken',
            method: 'post',
            data: qs.stringify({
                'refer_token': tokenTools.getReferToken()
            }),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            },
        })
            .then(res => {
                if (res.data.code === 1) {
                    tokenTools.setToken(res.data.data.token)
                    tokenTools.setReferToken(res.data.data.refer_token)
                    location.reload()
                } else {
                    if (lastCode !== '4xx') {
                        lastCode = '4xx'
                        message({
                            type: 'warning',
                            message: 'please login'
                        })
                    }
                    tokenTools.setToken('')
                    router.push({name: 'listlogin'})
                }
            })
    }
})

export default service
